<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="公告标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          @keyup.enter.native="handleQuery"
        >
          <el-option label="正常" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['page:notice:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['page:notice:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['page:notice:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['page:notice:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="noticeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="公告ID" align="center" prop="id" /> -->
      <el-table-column label="公告标题" align="center" prop="title" />
      <el-table-column label="公告内容" align="center" prop="context">
        <template slot-scope="scope">
          <div
            v-html="scope.row.context"
            style="width: 200px; height: 150px"
          ></div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="公告类型" align="center" prop="noticeType" /> -->
      <el-table-column label="公告状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <div slot="reference" class="name-wrapper">
              <el-tag
                size="medium"
                :type="scope.row.status === 0 ? 'danger' : 'success'"
                >{{ scope.row.status === 0 ? "停用" : "正常" }}</el-tag
              >
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        prop="filePath"
        align="center"
        label="首页展示图片"
      >
        <!-- 图片的显示 -->
        <template slot-scope="scope">
          <img
            v-show="scope.row.filePath"
            :src="BaseUrl + scope.row.filePath"
            min-width="300"
            height="150"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="文件" align="center" prop="file" /> -->
      <el-table-column label="公告时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.noticeTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['page:notice:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['page:notice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rowsPerPage"
      @pagination="getList"
    />

    <!-- 添加或修改通知公告对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="1">正常</el-radio-button>
            <el-radio-button label="0">停用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告时间" prop="time">
          <el-date-picker
            v-model="form.noticeTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择通知时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公告内容">
          <editor v-model="form.context" :min-height="192" />
        </el-form-item>

        <el-form-item v-show="form.filePath" label="通知图片" prop="picture">
          <img :src="form.filePath" style="width: 300px; height: 150px" />
        </el-form-item>
        <el-form-item label="上传" prop="remark">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :before-upload="beforeUplad"
            :on-success="filesuccess"
            :headers="headers"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="文件" prop="file">
          <file-upload v-model="form.file" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listNotice,
  getNotice,
  delNotice,
  delNotices,
  addNotice,
  updateNotice,
} from "@/api/page/notice";
import { getToken } from "@/utils/auth";
import { getFilebyId, delFilebyId } from "@/api/tool/file";

export default {
  name: "Notice",
  data() {
    return {
      isupload: false,
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      BaseUrl: process.env.VUE_APP_BASE_API,
      uploadUrl:
        process.env.VUE_APP_BASE_API + "/officialWebsite/notice/upload", // 上传的图片服务器地址
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        rowsPerPage: 10,
        title: null,
        // noticeType: null,
        context: null,
        status: null,
        pic: null,
        file: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "公告标题不能为空", trigger: "blur" },
        ],
        // noticeType: [
        //   { required: true, message: "公告类型不能为空", trigger: "change" },
        // ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    beforeUplad(file) {
      // if (this.form.fileId) {
      //   delFilebyId(this.form.fileId).then((res) => {
      //     if (res && res.code === 200) {
      //       // this.$message({
      //       //   message: "文件删除成功",
      //       //   type: "success",
      //       //   duration: 1500,
      //       // });
      //     } else {
      //       this.$message.error(data.msg);
      //     }
      //   });
      // }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 上传成功后的回调函数
    filesuccess(res, file, fileList) {
      if (res.code == 200) {
        this.isupload = true;
        this.form.fileId = res.data;
        // this.sizeForm.fileList.push(file);
        getFilebyId(res.data).then((res) => {
          if (res.code === 200) {
            this.form.filePath =
              process.env.VUE_APP_BASE_API + res.data.filePath;
            this.$message({
              message: "文件上传成功",
              type: "success",
              duration: 1500,
            });
          }
        });
        console.log("数据" + res.data);
      }
    },
    /** 查询通知公告列表 */
    getList() {
      this.loading = true;
      listNotice(this.queryParams).then((response) => {
        this.noticeList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      if (this.form.fileId && this.isupload) {
        delFilebyId(this.form.fileId).then((res) => {
          if (res && res.code === 200) {
            this.$message({
              message: "文件取消上传",
              type: "success",
              duration: 1500,
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      }
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        // noticeType: null,
        context: null,
        status: null,
        pic: null,
        file: null,
        noticeTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.fileList = [];
      this.isupload = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通知公告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getNotice(id).then((response) => {
        this.form = response.data;
        if (response.data.filePath) {
          this.form.filePath =
            process.env.VUE_APP_BASE_API + response.data.filePath;
        }
        this.open = true;
        this.title = "修改通知公告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateNotice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.id) {
        const id = row.id;
        this.$modal
          .confirm('是否确认删除通知公告编号为"' + id + '"的数据项？')
          .then(function () {
            return delNotice(id);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      } else {
        const ids = this.ids.join(",");
        this.$modal
          .confirm('是否确认删除通知公告编号为"' + ids + '"的数据项？')
          .then(function () {
            return delNotices(ids);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "page/notice/export",
        {
          ...this.queryParams,
        },
        `notice_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
